package com.maikang.exammall.handler;

import com.maikang.exammall.builder.TextBuilder;
import com.maikang.exammall.entity.User;
import com.maikang.exammall.entity.dto.PositionDTO;
import com.maikang.exammall.entity.dto.user.UserProfileDTO;
import com.maikang.exammall.repository.UserRepository;
import com.maikang.exammall.service.RedisService;
import com.maikang.exammall.util.MapUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import java.net.URISyntaxException;
import java.util.Map;
import java.util.Optional;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
@Log4j2
@RequiredArgsConstructor
public class LocationHandler extends AbstractHandler {
    private final RedisService redisService;
    private final UserRepository userRepository;
    private final MapUtil mapUtil;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        if (wxMessage.getMsgType().equals(XmlMsgType.LOCATION)) {
            //TODO 接收处理用户发送的地理位置消息
            try {
                log.info(" got location sent by a user, wxMessage: {}", wxMessage);
                String content = "感谢反馈，您的的地理位置已收到！";
                return new TextBuilder().build(content, wxMessage, null);
            } catch (Exception e) {
                log.error("位置消息接收处理失败", e);
                return null;
            }
        }

        //上报地理位置事件
        log.info("上报地理位置，纬度 : {}，经度 : {}，精度 : {}", wxMessage.getLatitude(), wxMessage.getLongitude(), String.valueOf(wxMessage.getPrecision()));
        try {
            UserProfileDTO user;
            Optional<User> byOpenId = userRepository.findByOpenId(wxMessage.getFromUser());
            if (!byOpenId.isPresent()) {
                throw new RuntimeException("cannot find user from db, wxMessage: " + wxMessage.toString());
            }
            user = new UserProfileDTO(byOpenId.get());
            PositionDTO pos = mapUtil.parseLocationFromLongitudeAndLatitude(wxMessage.getLongitude(), wxMessage.getLatitude());
            mapUtil.storePositionToRedis(user.getId(), pos);
        } catch (URISyntaxException e) {
            log.error("failed to handler position report from wechat, message: {}, error: {}", wxMessage, e.getMessage());
            e.printStackTrace();
        }
        return new TextBuilder().build("", wxMessage, null);
    }


}
